<template>
  <view class="ranking-container">
    <view class="header">
      <text class="title">积分排行榜</text>
      <text class="subtitle">只显示有积分的用户</text>
    </view>
    
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 排行榜列表 -->
    <view v-else-if="ranking.length > 0" class="ranking-list">
      <view 
        v-for="(user, index) in ranking" 
        :key="user.user_id" 
        class="ranking-item"
        :class="{ 'top-three': index < 3 }"
      >
        <view class="rank">
          <text v-if="index < 3" class="rank-icon">{{ getRankIcon(index) }}</text>
          <text v-else class="rank-number">{{ index + 1 }}</text>
        </view>
        <view class="user-info">
          <text class="user-name">{{ user.user_name }}</text>
          <text class="user-level">Lv.{{ user.level }}</text>
        </view>
        <view class="points">{{ user.points }}积分</view>
      </view>
    </view>
    
    <!-- 空状态 -->
    <view v-else class="empty-state">
      <view class="empty-icon">🏆</view>
      <text class="empty-title">暂无排行榜数据</text>
      <text class="empty-desc">还没有用户获得积分，快去发布动态赚取积分吧！</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getPointsRanking } from '@/api/points.js'
import { handleApiError } from '@/utils/error-handler.js'
import { validateBeforeOperation } from '@/utils/auth'

// 积分排行榜数据
const ranking = ref([])
const loading = ref(false)

// 获取排名图标
const getRankIcon = (index) => {
  const icons = ['🥇', '🥈', '🥉']
  return icons[index] || ''
}

// 获取积分排行榜
const fetchRanking = async () => {
  loading.value = true
  try {
    // 调试：检查存储的token和用户信息
    const token = uni.getStorageSync('token')
    const userInfo = uni.getStorageSync('user_info')
    const userState = uni.getStorageSync('userState')
    const userId = uni.getStorageSync('userId')
    
    console.log('调试信息 - Token:', token)
    console.log('调试信息 - UserInfo:', userInfo)
    console.log('调试信息 - UserState:', userState)
    console.log('调试信息 - UserId:', userId)
    
    // 使用统一的登录验证
    const isLoggedIn = validateBeforeOperation('查看积分排行榜')
    console.log('登录验证结果:', isLoggedIn)
    
    if (!isLoggedIn) {
      console.log('用户未登录，无法获取积分排行榜')
      return
    }
    
    console.log('开始调用积分排行榜API...')
    const response = await getPointsRanking()
    console.log('API响应原始数据:', response)
    console.log('响应类型:', typeof response)
    console.log('响应是否为数组:', Array.isArray(response))
    
    // 检查响应格式
    let rawData = []
    if (Array.isArray(response)) {
      rawData = response
      console.log('使用直接数组格式')
    } else if (response && Array.isArray(response.data)) {
      rawData = response.data
      console.log('使用response.data数组格式')
    } else if (response && response.data) {
      rawData = [response.data]
      console.log('使用response.data单对象格式')
    } else {
      rawData = []
      console.log('使用空数组格式')
    }
    
    // 过滤掉积分为0的用户
    ranking.value = rawData.filter(user => user.points > 0)
    console.log('过滤前数据长度:', rawData.length)
    console.log('过滤后数据长度:', ranking.value.length)
    
    console.log('积分排行榜数据:', ranking.value)
    console.log('排行榜长度:', ranking.value.length)
    
    // 检查每个用户的数据
    if (ranking.value.length > 0) {
      console.log('排行榜用户详情:')
      ranking.value.forEach((user, index) => {
        console.log(`第${index + 1}名:`, user)
      })
    }
  } catch (error) {
    console.error('获取积分排行榜错误:', error)
    handleApiError(error, '获取积分排行榜')
    ranking.value = []
  } finally {
    loading.value = false
  }
}

// 页面加载时获取排行榜
onMounted(() => {
  fetchRanking()
})
</script>

<style scoped>
.ranking-container {
  padding: 20rpx;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.header {
  text-align: center;
  margin-bottom: 30rpx;
  padding: 20rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.subtitle {
  font-size: 24rpx;
  color: #666;
  display: block;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid #f3f3f3;
  border-top: 4rpx solid #7B68EE;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

.ranking-list {
  background: #fff;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.ranking-item {
  display: flex;
  align-items: center;
  padding: 30rpx 20rpx;
  border-bottom: 1rpx solid #eee;
}

.ranking-item:last-child {
  border-bottom: none;
}

.ranking-item.top-three {
  background: linear-gradient(135deg, #fff8e1 0%, #fff3e0 100%);
}

.rank {
  width: 80rpx;
  text-align: center;
}

.rank-icon {
  font-size: 40rpx;
}

.rank-number {
  font-size: 32rpx;
  font-weight: bold;
  color: #999;
}

.top-three .rank-number {
  color: #ff9800;
}

.user-info {
  flex: 1;
  margin-left: 20rpx;
}

.user-name {
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
}

.user-level {
  font-size: 24rpx;
  color: #999;
  margin-left: 10rpx;
}

.points {
  font-size: 30rpx;
  color: #ff9800;
  font-weight: bold;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 20rpx;
  text-align: center;
}

.empty-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
}

.empty-title {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.empty-desc {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
}
</style>